<?php

namespace Sharks\Core\Persistence\QueryBuilder;

use Sharks\Core\Persistence\Db;
use Sharks\Core\Support\Log\Log;

/**
 * 删除查询
 * <pre>
 *      Query::createDelete()->from('SysUser')->get(); // 删除全部
 *      Query::createDelete()->from('SysUser')->eq('id', 1)->get(); // 删除id=1的行数据
 * </pre>
 */
class DeleteQuery extends AbstractExpressionQuery {

    protected $deleteQuery;
    protected $stmt;
    protected $identifier;

    public function __construct($identifier) {
        $this->deleteQuery = Db::connector($identifier)->createDeleteQuery();
        $this->identifier = $identifier;
    }

    /**
     * 删除
     * @param $table
     */
    public function from($table) {
        $this->deleteQuery->deleteFrom($table);
        return $this;
    }

    /**
     * 获取SQL 执行的返回值
     * @return bool
     * @throws \Sharks\Core\Exception\DatabaseException
     */
    public function get() {
        $stmt = $this->deleteQuery->prepare();
        $stmt->execute();

        $this->checkError($stmt);
        $rowCount = $stmt->rowCount();
        if ($rowCount == 0) {
            Log::debug("更新影响行数为0");
        }
        return $rowCount;
    }

    protected function getQuery() {
        return $this->deleteQuery;
    }
}